package com.tju.ocean_ecology_website.controller;

import com.tju.ocean_ecology_website.dto.ApiResponse;
import com.tju.ocean_ecology_website.dto.LoginRequest;
import com.tju.ocean_ecology_website.dto.LoginResponse;
import com.tju.ocean_ecology_website.dto.RegisterRequest;
import com.tju.ocean_ecology_website.dto.RegisterResponse;
import com.tju.ocean_ecology_website.dto.ValidationErrorResponse;
import com.tju.ocean_ecology_website.entity.User;
import com.tju.ocean_ecology_website.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private AuthService authService;

    /**
     * 用户登录
     * @param loginRequest 登录请求
     * @return 登录响应
     */
    @PostMapping("/login")
    public ResponseEntity<ApiResponse<LoginResponse>> login(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            LoginResponse loginResponse = authService.login(loginRequest);
            return ResponseEntity.ok(ApiResponse.success(loginResponse, "登录成功"));
        } catch (Exception e) {
            return ResponseEntity.status(401).body(ApiResponse.error(401, e.getMessage()));
        }
    }

    /**
     * 用户注册
     * @param registerRequest 注册请求
     * @return 注册结果
     */
    @PostMapping("/register")
    public ResponseEntity<ApiResponse<RegisterResponse>> register(@Valid @RequestBody RegisterRequest registerRequest) {
        try {
            RegisterResponse registerResponse = authService.registerAndGetResponse(registerRequest);
            return ResponseEntity.ok(ApiResponse.success(registerResponse, "注册成功"));
        } catch (Exception e) {
            // 创建错误响应
            Map<String, String[]> errors = new HashMap<>();

            // 根据异常消息判断错误类型
            if (e.getMessage().contains("用户名已存在")) {
                errors.put("username", new String[]{"用户名已存在"});
            } else if (e.getMessage().contains("邮箱已存在")) {
                errors.put("email", new String[]{"邮箱已存在"});
            } else if (e.getMessage().contains("无效的角色")) {
                errors.put("role", new String[]{"无效的角色值，必须是0（普通用户）、2（志愿者）或3（组织）"});
            }

            return ResponseEntity.badRequest().body(ApiResponse.error(400, e.getMessage(), errors));
        }
    }

    /**
     * 处理参数验证异常
     * @param ex 验证异常
     * @return 错误响应
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ApiResponse<ValidationErrorResponse>> handleValidationExceptions(MethodArgumentNotValidException ex) {
        // 收集所有验证错误
        Map<String, String[]> errors = ex.getBindingResult().getFieldErrors().stream()
                .collect(Collectors.groupingBy(
                        FieldError::getField,
                        Collectors.mapping(FieldError::getDefaultMessage, Collectors.toList())
                ))
                .entrySet().stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> entry.getValue().toArray(new String[0])
                ));

        // 创建验证错误响应
        ValidationErrorResponse validationErrorResponse = new ValidationErrorResponse(errors);

        return ResponseEntity.badRequest().body(ApiResponse.error(400, "请求参数验证失败", validationErrorResponse));
    }
}
